package org.goldfish.demo.apicall.analysis.code.upload.messager.impl.tongyi;

import jakarta.annotation.PostConstruct;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;

@Slf4j
@Getter
@Component
@PropertySource("client.properties")
public class Config {

    @Value("${key}")
    private String key;

    @Value("${model}")
    private String model;

    @Value("${incrementalOutput}")
    private String incrementalOutput;

    @PostConstruct
    public void checkParams() throws IllegalAccessException {
        Field[] fields = this.getClass().getDeclaredFields();
        StringBuilder missingFields = new StringBuilder();

        for (Field field : fields) {
            Value springDIValue = field.getAnnotation(Value.class);
            if (springDIValue == null) return;

            field.setAccessible(true);
            Object value = field.get(this);
            if (value == null) {
                missingFields.append(field.getName()).append(", ");
            } else {
                log.info("从 {} 向 {} 注入 {}",
                        springDIValue.value(),
                        field.getName(), value
                );
            }
        }
        PropertySource propertySourceAnnotation = getClass().getAnnotation(PropertySource.class);
        String propertySourceValue = "application.properties"; // 默认值
        if (propertySourceAnnotation != null && propertySourceAnnotation.value().length > 0) {
            propertySourceValue = propertySourceAnnotation.value()[0];
        }
        if (!missingFields.isEmpty()) {


            String msg = "配置文件缺少必要参数，请检查 " + propertySourceValue + " 中 tongyi.* 的配置，缺失字段: "
                    + missingFields.substring(0, missingFields.length() - 2);
            log.error(msg);
            throw new IllegalStateException(msg);

        }

        log.info("{} 初始化完成", propertySourceValue);
    }
}
